<template>
    <el-tree ref="treeRef" :props="options" node-key="permissionId" :data="lists" show-checkbox @check-change="handleCheckChange" :default-expanded-keys="defaultExpandedKeys" :default-checked-keys="modelValue"/>
</template>
<script setup>
import { ref, defineProps,onMounted } from 'vue';
import {getAuthTree} from '@/api/user'

const props = defineProps(['modelValue','disabled'])
const emit = defineEmits(['update:modelValue'])
const options = ref({
  id: 'permissionId',
  label: 'name',
  children: 'children',
  disabled: 'disabled' // 禁用标志
})
const lists = ref([])
const defaultExpandedKeys = ref([])
const treeRef = ref(null)
onMounted(()=>{ 
    getLists()
})

const getLists = async ()=>{
    const res = await getAuthTree()
    if (res.code == 200) {
        lists.value = res.data
        //设置默认展开
        lists.value.forEach(item => {
            defaultExpandedKeys.value.push(item.permissionId)
        });

        // 设置禁用
        console.log("props.disabled===",props.disabled)
        if(props.disabled){
            setField(lists.value,'disabled')
        }
        
    }
}
// 给数据对象添加一个字段
const setField = (arr,field)=>{
    for(let i=0;i<arr.length;i++){
        //console.log("permissionId:",arr[i].permissionId)
        arr[i][field] = true
        if(arr[i].children && arr[i].children.length>0){
            setField(arr[i].children,field) // 有子菜单，继续条用本身循环
        }
    }
}

const handleCheckChange =(data)=>{
    // const arr = treeRef.value.getCheckedNodes(false, false)
    const keys = treeRef.value.getCheckedKeys(false)
    emit('update:modelValue',keys)
}

</script>